package com.mini.service;

import com.mini.constant.CooManagerTypeEnum;
import com.mini.constant.CooOperationEnum;
import com.mini.constant.CooTabTypeEnum;
import com.mini.model.*;
import com.mini.repository.BusinessRequirementPlanNeedRepository;
import com.mini.req.RequirementPlanFormReq;
import com.mini.req.RequirementPlanTableReq;
import com.mini.vo.UserVO;
import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 项目名称：traditional-business
 * 类 名 称：CooperativeAndPlanLogRecordService
 * 类 描 述：合作管理和需求规划操作日志记录
 * 创建时间：2021/1/29 下午2:56
 * 创 建 人：zhanghuiying
 */
@Slf4j
@Service
public class CooperativeAndPlanLogRecordService extends BaseService {
    @Autowired
    private CooperativeService cooperativeService;
    @Autowired
    private MiniAdminService miniAdminService;
    @Autowired
    private BusinessOperationRecordService operationRecordService;

    /**
     * 需求规划 【日名片需求/截止时间/名片余量设置/A/B模式设置】类型 添加操作记录
     */
    public void addRequirementPlanBaseLog(Long oldId,Long oldQuantumArmyGroupId,Date EndTime,Integer oldCardCount,String oldReceivingResidue,String oldPattern, BusinessRequirementPlanBaseBean newOne) {
        String quantumArmyGroupName = miniAdminService.getDeptName(newOne.getQuantumArmyGroupId());
        UserVO userSimpleInfo = miniAdminService.getUserSimpleInfo(newOne.getCreateUserId());
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat planFormat = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat datef = new SimpleDateFormat("HH:mm");
        String format = dateFormat.format(new Date());
        String planDate=planFormat.format(newOne.getPlanDate());
        String  newEndTime=datef.format(newOne.getEndTime());
        if (newEndTime.equals("23:59")){
            newEndTime="24:00";
        }
        //新增一条记录
        if (null == oldId) {
            String create = format + "" + userSimpleInfo.getEmail() + " 修改 " +planDate+" "+ quantumArmyGroupName + "（" + newOne.getQuantumArmyGroupId() + "）的 需求设置 " + " 从 0/24:00/否/A模式 修改至 " +
                    newOne.getCardCount() + "/" + newEndTime + "/" + newOne.makeReceivingResidue() + "/" + newOne.makePattern();
            operationRecordService.save(null, " ",
                    1, create, newOne.getUpdateUserId(),
                    userSimpleInfo.getNickname(), 1, userSimpleInfo.getUsername(), userSimpleInfo.getRoleName(), new Date());
            return;
        }
        String oldEndTime=datef.format(EndTime);
        if (oldEndTime.equals("23:59")){
            oldEndTime="24:00";
        }
        if (!newEndTime.equals(oldEndTime)||!oldCardCount.equals(newOne.getCardCount())||!oldReceivingResidue.equals(newOne.makeReceivingResidue())||!oldPattern.equals(newOne.makePattern())){
            String change = format + "" + userSimpleInfo.getEmail() + " 修改 " +planDate+" "+ quantumArmyGroupName + "（" + oldQuantumArmyGroupId + "）的 需求设置 " + " 从 " + oldCardCount + "/" + oldEndTime + "/" + oldReceivingResidue + "/" + oldPattern +
                    " 修改至 " + newOne.getCardCount() + "/" + newEndTime + "/" + newOne.makeReceivingResidue() + "/" + newOne.makePattern();

            operationRecordService.save(null, " ",
                    1, change, newOne.getUpdateUserId(),
                    userSimpleInfo.getNickname(), 1, userSimpleInfo.getUsername(), userSimpleInfo.getRoleName(), new Date());
        }
    }

    /**
     * 需求规划 删除整个项目的需求规划 操作记录
     */
    public void deleteRequirementPlanBaseLog(Long userId, Long quantumArmyGroupId,Date planDate, List<BusinessRequirementPlanFormBean> businessRequirementPlanFormBeans, BusinessRequirementPlanTableBean tableBean, String token) {
        String quantumArmyGroupName = miniAdminService.getDeptName(quantumArmyGroupId);
        UserVO userSimpleInfo = miniAdminService.getUserSimpleInfo(userId);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat planFormat = new SimpleDateFormat("yyyy-MM-dd");
        String plan=planFormat.format(planDate);
        String format = dateFormat.format(new Date());
        Map<Integer, String> projectMap = cooperativeService.getProjectMap(token);
        String projectName = projectMap.get(tableBean.getProjectId());

        List<String> channelCode = businessRequirementPlanFormBeans.stream()
                .map(BusinessRequirementPlanFormBean::getChannelCode)
                .collect(Collectors.toList());
        String channel = makeChannel(token, channelCode);

        Map<Long, List<BusinessRequirementPlanFormBean>> mapTask = businessRequirementPlanFormBeans.stream().sorted(Comparator.comparing((b) -> b.getId())).collect(Collectors.groupingBy((a) -> a.getNeedId()));
        List<String> provinceCode = new ArrayList<>();
        for (Map.Entry<Long, List<BusinessRequirementPlanFormBean>> formOne :
                mapTask.entrySet()) {

            List<String> pro = formOne.getValue().stream()
                    .map(BusinessRequirementPlanFormBean::getProvince)
                    .collect(Collectors.toList());
            String p = String.join(",", pro);
            if (!provinceCode.contains(p)) {
                provinceCode.add(p);
            }
        }
        StringBuffer province = makeProvince(token, provinceCode);
        String log = format + " " + userSimpleInfo.getEmail() + " 删除 " +plan+" "+ quantumArmyGroupName + "（" + quantumArmyGroupId.longValue() + "）" + "的需求拆分—— " +
                projectName + "/" + channel + "/" + province;
        operationRecordService.save(null, "",
                1, log, userId,
                userSimpleInfo.getNickname(), 1, userSimpleInfo.getUsername(), userSimpleInfo.getRoleName(), new Date());
    }

    /**
     * 需求规划 创建整个项目的需求规划 操作记录
     */
    public void addCreateAndDeleteLog(Long userId, Long quantumArmyGroupId,Date planDate, RequirementPlanTableReq table, String token) {

        String quantumArmyGroupName = miniAdminService.getDeptName(quantumArmyGroupId);
        UserVO userSimpleInfo = miniAdminService.getUserSimpleInfo(userId);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat planFormat = new SimpleDateFormat("yyyy-MM-dd");
        String plan=planFormat.format(planDate);
        String format = dateFormat.format(new Date());
        Map<Integer, String> projectMap = cooperativeService.getProjectMap(token);
        Map<String, String> channelMap = cooperativeService.getChannelMap(token);
        String projectName = projectMap.get(table.getProjectId());

        List<String> channelCode = table.getRequirementPlanFormRes().stream()
                .map(RequirementPlanFormReq::getChannelCode)
                .collect(Collectors.toList());
        String channel = makeChannel(token, channelCode);

        List<String> provinceCode = table.getRequirementPlanFormRes().stream()
                .map(RequirementPlanFormReq::getProvince)
                .distinct()
                .collect(Collectors.toList());
        StringBuffer province = makeProvince(token, provinceCode);

        String log = format + " " + userSimpleInfo.getEmail() + " 创建 " +plan+" "+ quantumArmyGroupName + "（" + quantumArmyGroupId.longValue() + "）" + "的需求拆分—— " +
                projectName + "/" + channel + "/" + province;
        operationRecordService.save(null, " ",
                1, log, userId,
                userSimpleInfo.getNickname(), 1, userSimpleInfo.getUsername(), userSimpleInfo.getRoleName(), new Date());

        for (RequirementPlanFormReq form
                : table.getRequirementPlanFormRes()
        ) {
            List<String> proList = new ArrayList<>();
            proList.add(form.getProvince());
            StringBuffer pro = makeProvince(token, proList);
            String cha = channelMap.get(form.getChannelCode());

            String needLog = format + " " + userSimpleInfo.getEmail() + " 创建 " +plan+" "+ quantumArmyGroupName + "（" + quantumArmyGroupId.longValue() + "）" + "的需求拆分——( " +
                    projectName + "/" + cha + "/" + pro + ")" + " 无至" + form.getNeedCount();
            operationRecordService.save(null, " ",
                    1, needLog, userId,
                    userSimpleInfo.getNickname(), 1, userSimpleInfo.getUsername(), userSimpleInfo.getRoleName(), new Date());
        }
    }

    /**
     * 需求规划 修改整个项目的需求规划 修改需求条件、修改需求上限 操作记录
     */
    public void updateCreateAndDeleteLog(Long userId, Long quantumArmyGroupId,Date planDate, List<BusinessRequirementPlanTableAndForm> businessRequirementPlanTableAndForms, RequirementPlanTableReq table, String token) {
        String quantumArmyGroupName = miniAdminService.getDeptName(quantumArmyGroupId);
        UserVO userSimpleInfo = miniAdminService.getUserSimpleInfo(userId);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat planFormat = new SimpleDateFormat("yyyy-MM-dd");
        String plan=planFormat.format(planDate);
        String format = dateFormat.format(new Date());
        Map<Integer, String> projectMap = cooperativeService.getProjectMap(token);
        Map<String, String> channelMap = cooperativeService.getChannelMap(token);
        Map<String, String> provinceMap = cooperativeService.getProvinceMap(token);
        String projectName = projectMap.get(table.getProjectId());

//      获得新的项目渠道省份
        List<String> channelCode = table.getRequirementPlanFormRes().stream()
                .map(RequirementPlanFormReq::getChannelCode)
                .collect(Collectors.toList());
        String channel = makeChannel(token, channelCode);
        List<String> provinceCode = table.getRequirementPlanFormRes().stream()
                .map(RequirementPlanFormReq::getProvince)
                .distinct()
                .collect(Collectors.toList());
        StringBuffer province = makeProvince(token, provinceCode);

        Boolean formLog=false;
        for (RequirementPlanFormReq form
                : table.getRequirementPlanFormRes()
        ) {
            List<String> proList = new ArrayList<>();
            proList.add(form.getProvince());
            StringBuffer pro = makeProvince(token, proList);
            String cha = channelMap.get(form.getChannelCode());
            if (Objects.nonNull(form.getNeedId())) {
                List<BusinessRequirementPlanTableAndForm> collect = businessRequirementPlanTableAndForms.stream()
                        .filter(f -> f.getNeedId().equals(form.getNeedId()))
                        .collect(Collectors.toList());
                Integer oldCount = collect.get(0).getNeedCount();
                if (!oldCount.equals(form.getNeedCount())) {
                    formLog=true;
                    String needLog = format + " " + userSimpleInfo.getEmail() + " 修改 " +plan+" "+ quantumArmyGroupName + "（" + quantumArmyGroupId.longValue() + "）" + "的需求拆分——( " +
                            projectName + "/" + cha + "/" + pro + ")" + oldCount + "至" + form.getNeedCount();
                    operationRecordService.save(null, "",
                            1, needLog, userId,
                            userSimpleInfo.getNickname(), 1, userSimpleInfo.getUsername(), userSimpleInfo.getRoleName(), new Date());
                }

            } else {
                formLog=true;
                String needLog = format + " " + userSimpleInfo.getEmail() + " 修改 " +plan+" "+ quantumArmyGroupName + "（" + quantumArmyGroupId.longValue() + "）" + "的需求拆分——( " +
                        projectName + "/" + cha + "/" + pro + ")" + " 无至" + form.getNeedCount();
                operationRecordService.save(null, " ",
                        1, needLog, userId,
                        userSimpleInfo.getNickname(), 1, userSimpleInfo.getUsername(), userSimpleInfo.getRoleName(), new Date());
            }
        }
        if (formLog){
//      获得旧的项目渠道省份
            Map<String, List<BusinessRequirementPlanTableAndForm>> byChannel = businessRequirementPlanTableAndForms.stream().sorted(Comparator.comparing((b) -> b.getId())).collect(Collectors.groupingBy((a) -> a.getChannelCode()));
            List<BusinessRequirementPlanTableAndForm> businessRequirementPlanTableAndForms1 = byChannel.get(businessRequirementPlanTableAndForms.get(0).getChannelCode());
            Map<Long, List<BusinessRequirementPlanTableAndForm>> mapTask = businessRequirementPlanTableAndForms1.stream().sorted(Comparator.comparing((b) -> b.getId())).collect(Collectors.groupingBy((a) -> a.getNeedId()));

            String oldProject = projectMap.get(businessRequirementPlanTableAndForms.get(0).getProjectId());
            List<String> oldchannelCode = businessRequirementPlanTableAndForms.stream()
                    .map(BusinessRequirementPlanTableAndForm::getChannelCode)
                    .distinct()
                    .collect(Collectors.toList());
            String oldchannel = makeChannel(token, oldchannelCode);
            StringBuffer oldprovince = new StringBuffer();
            int count = 0;
            for (Map.Entry<Long, List<BusinessRequirementPlanTableAndForm>> entry : mapTask.entrySet()) {
                count++;
                List<String> provinceName = new ArrayList<>();
                for (BusinessRequirementPlanTableAndForm p :
                        entry.getValue()) {
//                  获取省份名称
                    provinceName.add(provinceMap.get(p.getProvince()));
                }
                String join = String.join(",", provinceName);
                if (count == mapTask.entrySet().size()) {
                    oldprovince = oldprovince.append(join);
                } else {
                    oldprovince = oldprovince.append(join).append("、");
                }
            }
            String conditionsLog = format + " " + userSimpleInfo.getEmail() + " 修改 " +plan+" "+ quantumArmyGroupName + "（" + quantumArmyGroupId.longValue() + "）" + "的需求拆分—— 【" +
                    oldProject + "/" + oldchannel + "/" + oldprovince + "】至 【" + projectName + "/" + channel + "/" + province + "】";
            operationRecordService.save(null, "",
                    1, conditionsLog, userId,
                    userSimpleInfo.getNickname(), 1, userSimpleInfo.getUsername(), userSimpleInfo.getRoleName(), new Date());
        }
    }

    //渠道拼接
    public String makeChannel(String token, List<String> channelCode) {
        Map<String, String> channelMap = cooperativeService.getChannelMap(token);
        List<String> channelName = new ArrayList<>();
        channelCode.stream()
                .distinct()
                .forEach(c -> {
                    channelName.add(channelMap.get(c));
                });
        String channelNames = String.join("、", channelName);
        return channelNames;
    }

    //省份拼接
    public StringBuffer makeProvince(String token, List<String> provinceCode) {
        Map<String, String> provinceMap = cooperativeService.getProvinceMap(token);
        StringBuffer provinceEnd = new StringBuffer();
        for (int i = 0; i < provinceCode.size(); i++) {
            List<String> provinceName = new ArrayList<>();
            List<String> province = Arrays.asList(provinceCode.get(i).split(","));
            province.stream().forEach(p -> {
                provinceName.add(provinceMap.get(p));
            });
            String ch = String.join(",", provinceName);
            if (i == provinceCode.size() - 1) {
                provinceEnd.append(ch);
            } else {
                provinceEnd.append(ch).append("、");
            }
        }
        return provinceEnd;
    }

    /**
     * 合作管理 操作记录日志
     */
    public void CooperativeLog(Long userId, Integer listType,Integer managerType, Integer operation, BusinessCooperativeBean cooperativeBean,String token){

        UserVO userSimpleInfo = miniAdminService.getUserSimpleInfo(userId);
        UserVO throwUser = miniAdminService.getUserSimpleInfo(cooperativeBean.getThrowUserId());
        UserVO createUser = miniAdminService.getUserSimpleInfo(cooperativeBean.getCreateUserId());

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormat.format(new Date());
        Map<Integer, String> projectMap = cooperativeService.getProjectMap(token);
        Map<String, String> channelMap = cooperativeService.getChannelMap(token);
        Map<String, String> provinceMap = cooperativeService.getProvinceMap(token);

        String projectName = projectMap.get(cooperativeBean.getProjectId());
        String channelName=channelMap.get(cooperativeBean.getAdChannelCode());
        String provinceName=provinceMap.get(cooperativeBean.getThrowProvinceCode());
        String quantumArmyGroupName = miniAdminService.getDeptName(cooperativeBean.getQuantumArmyGroupId());

        String list="";
        for (CooTabTypeEnum tab :
                CooTabTypeEnum.values() ) {
            if (listType.equals(tab.getCode())){
                list=tab.getDesc();
            }
        }
        String manager="";
        for (CooManagerTypeEnum man :
                CooManagerTypeEnum.values() ) {
            if (managerType.equals(man.getCode())){
                manager=man.getDesc();
            }
        }
        String opera="";
        for (CooOperationEnum ope :
                CooOperationEnum.values()) {
            if (operation.equals(ope.getCode())){
                opera=ope.getDesc();
            }
        }
        String Log = "";
        if (listType.equals(CooTabTypeEnum.applyList.getCode())) {
            Log = format + " " + userSimpleInfo.getEmail() + "在【"+manager+list+"】中" +opera+ "【"+createUser.getNickname()+"/"+throwUser.getNickname()+"/"+quantumArmyGroupName+"/"+projectName+"/"+channelName+"/"+provinceName+"】("+cooperativeBean.getId()+")";
        }else {
            Log = format + " " + userSimpleInfo.getEmail() + "在【"+manager+list+"】中" +opera+ "【"+throwUser.getNickname()+"/"+quantumArmyGroupName+"/"+projectName+"/"+channelName+"/"+provinceName+"】("+cooperativeBean.getId()+")";
        }
        operationRecordService.save(null, "",
                1, Log, userId,
                userSimpleInfo.getNickname(), 3, userSimpleInfo.getUsername(), userSimpleInfo.getRoleName(), new Date());
    }
}
